import { LockOutlined, UserOutlined } from '@ant-design/icons';
import { Button, Form, Input, message } from 'antd';
import { useState } from 'react';
import { useNavigate } from 'react-router-dom';
import LogoUrl from '../../assets/svg/react.svg?url';
import './index.css';

const LoginForm = () => {
  const [isRegisterMode, setIsRegisterMode] = useState(false);
  const navigate = useNavigate();

  const users: Record<string, string> = {
    'admin': '123456', // 预设管理员账号
    'test': '123'
  };

  const handleFinish = (values: { username: string; password: string }) => {
    const { username, password } = values;

    if (isRegisterMode) {
      if (users[username]) {
        message.error('用户名已存在');
      } else {
        users[username] = password;
        message.success('注册成功！');
        setIsRegisterMode(false);
      }
    } else {
      if (users[username] && users[username] === password) {
        message.success('登录成功！');
        navigate('/home'); // 登录成功后跳转
      } else {
        message.error('用户名或密码错误');
      }
    }
  };

  return (
    <Form
      name="login"
      initialValues={{ remember: true }}
      style={{ maxWidth: 360 }}
      onFinish={handleFinish}
    >
      {/* 提示信息 */}
      <Form.Item>
        <div className="login-form-hint">
          <span>i</span>
          用户名：admin，密码：123456
        </div>
      </Form.Item>
      {/* 表单输入项 */}
      <Form.Item
        name="username"
        rules={[{ required: true, message: '请输入用户名!' }]}
      >
        <Input prefix={<UserOutlined />} placeholder="用户名" />
      </Form.Item>
      <Form.Item
        name="password"
        rules={[{ required: true, message: '请输入密码!' }]}
      >
        <Input
          prefix={<LockOutlined />}
          type="password"
          placeholder="密码"
          autoComplete="current-password"
        />
      </Form.Item>
      <Form.Item>
        <Button block type="primary" htmlType="submit" style={{ background: '#2db7f5', borderColor: '#2db7f5' }}>
          登录
        </Button>
      </Form.Item>
    </Form>
  );
};

const Login = () => {
  return (
    <div className="login-container">
      <div className="left-panel">
        <img src={LogoUrl} alt="React Logo" style={{ width: '100px' }} />
      </div>
      <div className="right-panel">
        <div className="login-form-container">
          <h1 style={{ textAlign: 'center', marginBottom: '24px' }}>React Vite Admin</h1>
          <LoginForm />
        </div>
      </div>
    </div>
  );
};

export default Login;